// 引入 API 方法
import { getUser } from "@/api/user.js";

const state = {
  userList: [], // 存储从 JSON 获取的所有用户数据
};

const mutations = {
  SET_USER_LIST(state, list) {
    state.userList = list;
    localStorage.setItem("vuex-users", JSON.stringify(list)); // 新增本地存储
  },
  ADD_USER(state, user) {
    state.userList.push(user);
    localStorage.setItem("vuex-users", JSON.stringify(state.userList)); // 新增本地存储
  },
  UPDATE_USER(state, updatedUser) {
    const index = state.userList.findIndex((u) => u.id === updatedUser.id);
    if (index > -1) {
      state.userList.splice(index, 1, updatedUser);
      localStorage.setItem("vuex-users", JSON.stringify(state.userList));
    }
  },
};

const actions = {
  async addUser({ commit }, user) {
    // 新增 addUser action
    commit("ADD_USER", user);
    return Promise.resolve();
  },
  async loadUserList({ commit }) {
    try {
      const localData = localStorage.getItem("vuex-users");
      if (localData) {
        commit("SET_USER_LIST", JSON.parse(localData)); // 优先读取本地数据
        return;
      }
      const response = await getUser();
      commit("SET_USER_LIST", response.data);
    } catch (error) {
      console.error("加载用户数据失败:", error);
    }
  },

  // 登录逻辑
  async userLogin({ commit, state }, credentials) {
    // 从 userList 中匹配用户
    const user = state.userList.find(
      (u) =>
        u.username === credentials.username &&
        u.password === credentials.password
    );

    if (user) {
      commit("SET_LOGIN_PERSON", user, { root: true }); // 添加第三个参数
      return Promise.resolve(user);
    } else {
      return Promise.reject(new Error("用户名或密码错误"));
    }
  },
  async updateUser({ commit }, user) {
    commit("UPDATE_USER", user);
    localStorage.setItem("vuex-users", JSON.stringify(state.userList));
    return Promise.resolve();
  },
};

export default {
  namespaced: true,
  state,
  mutations,
  actions,
};
